package com.xjl.aop.springbootaop.aspect;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xjl.aop.springbootaop.annotation.PermissionAnnotation;
import com.xjl.aop.springbootaop.service.AopService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import javax.annotation.Resource;
import java.lang.reflect.Method;

@Aspect
@Component
@Order(1)
public class PermissionFirstAdvice {

    @Resource
    private AopService aopService;

    // 定义一个切面，括号内写入第1步中自定义注解的路径
    @Pointcut("@annotation(com.xjl.aop.springbootaop.annotation.PermissionAnnotation)")
    private void permissionCheck() {
    }

    @Around("permissionCheck()")
    public Object permissionCheckFirst(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("===================第一个切面开始===================：" + System.currentTimeMillis());

        //获取请求参数，详见接口类
        Object[] objects = joinPoint.getArgs();
        Long id = ((JSONObject) objects[0]).getLong("id");
        String name = ((JSONObject) objects[0]).getString("name");
        System.out.println("id1->>>>>>>>>>>>>>>>>>>>>>" + id);
        System.out.println("name1->>>>>>>>>>>>>>>>>>>>>>" + name);

        // id小于0则抛出非法id的异常
        if (id < 0) {
            return JSON.parseObject("{\"message\":\"illegal id\",\"code\":403}");
        }
        Method perClass = ReflectionUtils.getAllDeclaredMethods(joinPoint.getTarget().getClass())[0];
        PermissionAnnotation permissionAnnotation = AnnotationUtils.findAnnotation(perClass,PermissionAnnotation.class);
        String module = permissionAnnotation.value();
        System.out.println("模块名称->>>>>>>>>>>>>>>>>>>>>>" + module);

        //测试异步处理，必须分开调用
        aopService.testMethod();
        aopService.ansyMethod();

        joinPoint.proceed();
        System.out.println("===================第一个切面结束===================：" + System.currentTimeMillis());
        return JSON.parseObject("{\"message\":\"SUCCESS\",\"code\":300}");
    }


}
